﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OBDUDSUtils.EtasCAN;
using OBDUDSUtils.CNNMode;
using OBDUDSUtils.Common;
using DeviceTestStand.Properties;

namespace DeviceTestStand
{
    public partial class FrmFlashECU : Form
    {
        private DiagData device;
        private Es581Manage es581;
        private string messageFile;

        public FrmFlashECU()
        {
            InitializeComponent();
        }

        private void FrmFlashECU_Load(object sender, EventArgs e)
        {
            this.messageFile = System.Environment.CurrentDirectory + "\\Data\\";
            this.device = new DiagData();
            this.device.EtasDevice = new EtasCANConfig();
            this.es581 = new Es581Manage();
            this.device.CodesResult = new List<string>();
            this.device.OperateMode = RunMode.UDS;
            this.device.EtasDevice.EsNetWork = "HSCAN";
            this.device.EtasDevice.IsExtendedID = false;
            this.device.OperateMode = RunMode.UDS_MESE6;//default
            this.device.IsSaveMessage = true;

            this.es581.InitCANDevice(ref this.device);
            //test
            //var send = new byte[] { 0x11, 0x22, 0x33, 0x44 };
            //encipher(2, send);

            this.es581.EsOBDMessageEvents += Es581_EsOBDMessageEvents;
            this.btn_readVIN.Click += Btn_readVIN_Click;
            this.btn_writeVIN.Click += Btn_writeVIN_Click;
            this.tool_link.Click += Tool_link_Click;
            this.tool_close.Click += Tool_close_Click;

            this.rbtn_mese6.CheckedChanged += Rbtn_mese6_CheckedChanged;
            this.rbtn_mese8.CheckedChanged += Rbtn_mese8_CheckedChanged;
            this.rbtn_mt053.CheckedChanged += Rbtn_mt053_CheckedChanged;
            this.rbtn_us61.CheckedChanged += Rbtn_us61_CheckedChanged;
        }

        private void Rbtn_us61_CheckedChanged(object sender, EventArgs e)
        {
            this.device.OperateMode = RunMode.UDS_UP6;
        }

        private void Rbtn_mt053_CheckedChanged(object sender, EventArgs e)
        {
            this.device.OperateMode = RunMode.UDS_MT05;
        }

        private void Rbtn_mese8_CheckedChanged(object sender, EventArgs e)
        {
            this.device.OperateMode = RunMode.UDS_MESE8;
        }

        private void Rbtn_mese6_CheckedChanged(object sender, EventArgs e)
        {
            this.device.OperateMode = RunMode.UDS_MESE6;
        }

        private void Tool_close_Click(object sender, EventArgs e)
        {
            this.es581.CloseEtas(ref this.device);
            this.tool_close.Enabled = false;
            this.tool_link.Enabled = true;
            this.tool_close.Image = Resources.close_device2;
        }

        private void Tool_link_Click(object sender, EventArgs e)
        {
            this.es581.OpenEtas(ref this.device);
            if (this.device.CANConnectStatus)
            {
                this.tool_link.Image = Resources.connect_device2;
                this.tool_close.Image = Resources.close_device1;
                this.tool_close.Enabled = true;
                this.tool_link.Enabled = false;
            }
            else
            {
                MessageBox.Show("打开设备失败！");
            }
        }

        private void Btn_writeVIN_Click(object sender, EventArgs e)
        {
            //将VIN码写入ECU
            var barCodeInput = this.tb_barCode_Write.Text;
            if (!barCodeInput.Contains("\n"))
                return;
            barCodeInput = barCodeInput.Trim();//去掉换行符
            this.tb_barCode_Write.Clear();
            if (barCodeInput.Length != 17)
            {
                this.tb_status.Text = "VIN码长度不匹配，请重新输入！";
                return;
            }

            //判断设备是否连接
            if (!this.device.CANConnectStatus)
            {
                return;
            }
            //判断配置条件是否满足


            //判断条码是否与当前设备或平台匹配
            FirstWriteRequest();
        }

        private void FirstWriteRequest()
        {
            switch (this.device.OperateMode)
            {
                case RunMode.UDS_MESE6:
                    {
                        byte[] data = new byte[] { 0x02, 0x10, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };//进入扩展会话模式
                        this.device.ModeType = DiagBasic.ModelSID.UDS_DID_Write;

                        SendMessage(data, 0, 8);
                    }
                    break;
                case RunMode.UDS_MESE8:
                    {
                        byte[] data = new byte[] { 0x02, 0x10, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };//进入扩展会话模式
                        this.device.ModeType = DiagBasic.ModelSID.UDS_DID_Write;

                        SendMessage(data, 0, 8);
                        break;
                    }
                case RunMode.UDS_MT05:
                    {
                        byte[] data = new byte[] { 0x02, 0x10, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 };//进入扩展会话模式
                        this.device.ModeType = DiagBasic.ModelSID.UDS_DID_Write;

                        SendMessage(data, 0, 8);
                    }
                    break;
                case RunMode.UDS_UP6:
                    {
                        byte[] data = new byte[] { 0x02, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };//进入扩展会话模式
                        this.device.ModeType = DiagBasic.ModelSID.UDS_DID_Write;

                        SendMessage(data, 0, 8);
                    }
                    break;
            }
        }

        private void Btn_readVIN_Click(object sender, EventArgs e)
        {
            ReadDID("0xf190");//读取汽车VIN码
        }

        private void Es581_EsOBDMessageEvents(List<CANBasic.VCI_CAN_OBJ> data)
        {
            switch (this.device.OperateMode)
            {
                case RunMode.UDS_MESE6:
                    {
                        AnalysisData(data);
                        break;
                    }
                case RunMode.UDS_MESE8:
                    {
                        AnalysisData(data);
                        break;
                    }
                case RunMode.UDS_MT05:
                    {
                        AnalysisData(data);
                        break;
                    }
                case RunMode.UDS_UP6:
                    {
                        AnalysisData(data);
                        break;
                    }
            }
        }

        private void AnalysisData(List<CANBasic.VCI_CAN_OBJ> data)
        {
            switch (this.device.ModeType)
            {
                case DiagBasic.ModelSID.UDS_DID_Read:
                    AnalysisUdsDid(data, 0x62);
                    break;
                case DiagBasic.ModelSID.UDS_DID_Write:
                    {
                        RecAnalysisWriteData(data);
                        break;
                    }
            }
        }

        private void RecAnalysisWriteData(List<CANBasic.VCI_CAN_OBJ> data)
        {
            switch (this.device.OperateMode)
            {
                case RunMode.UDS_MESE6:
                    ProcessMese6(data);
                    break;
                case RunMode.UDS_MESE8:
                    ProcessMese6(data);
                    break;
                case RunMode.UDS_MT05:
                    ProcessMese6(data);
                    break;
                case RunMode.UDS_UP6:
                    ProcessUs61(data);
                    break;
            }
        }

        private async void ProcessMese6(List<CANBasic.VCI_CAN_OBJ> data)
        {
            for (int i = 0; i < data.Count; i++)
            {
                if (data[i].Data[1] == 0x50)//扩展会话模式的回复 50 03 00 32 01 F4
                {
                    if (data[i].Data[2] == 0x03)
                    {
                        //进入10 02模式
                        //SendMessage(new byte[] { 0x02, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);

                        //请求种子，发送27 01
                        SendMessage(new byte[] { 0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    }
                    //else if (data[i].Data[2] == 0x02)
                    //{
                    //    //请求种子，发送27 01
                    //    SendMessage(new byte[] { 0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    //}
                }
                else if (data[i].Data[1] == 0x67)
                {
                    if (data[i].Data[2] == 0x01)//请求种子27的回复
                    {
                        //计算密钥
                        var keys = Encipher(2, new byte[] { data[i].Data[3], data[i].Data[4], data[i].Data[5], data[i].Data[6] });

                        //发送密钥进行验证
                        SendMessage(new byte[] { 0x06, 0x67, 0x02, keys[0], keys[1], keys[2], keys[3] }, 0, 8);
                    }
                    else if (data[i].Data[2] == 0x02)//发送密钥的回复
                    {
                        //开始发送VIN码
                        byte[] vins;
                        GetVinMessage(out vins);
                        if (vins.Length > 5)//发送多帧，默认数据长度为多帧
                        {
                            SendMessage(new byte[] { 0x10, 0x14, 0x2e, 0xf1, 0x90, vins[0], vins[1], vins[2] }, 0, 8);
                        }
                    }
                }
                else if (data[i].Data[0] == 0x30)
                {
                    if (data[i].Data[1] == 0x00 && data[i].Data[2] == 0x02)
                    {
                        byte[] vins;
                        GetVinMessage(out vins);
                        for (int f = 3; f < vins.Length; f = f + 8)
                        {
                            SendMessage(vins, f, 8);
                            await Task.Delay(10);
                        }
                    }
                }
                else if (data[i].Data[1] == 0x6e)
                {
                    if (data[i].Data[2] == 0xf1 && data[i].Data[3] == 0x90)
                    {
                        //写入VIN成功
                        LogHelper.Log.Info("VIN写入成功");
                        UpdateLbxStatus("VIN写入成功");
                    }
                }
                else if (data[i].Data[1] == 0x7f)//错误反馈
                {
                    if (data[i].Data[2] == 0x10)//进入10 02模式的错误反馈 0x03 0x7f 0x10 0x7e 0xaa 0xaa 0xaa 0xaa
                    {
                        UpdateLbxStatus($"进入诊断会话控制服务失败-扩展会话，反馈指令：{BitConverter.ToString(data[i].Data)}");
                    }
                    else if (data[i].Data[2] == 0x27)//请求种子的错误反馈 0x03 0x7f 0x27 0x7f 0x0a 0x0a 0x0a, 0x0a
                    {
                        UpdateLbxStatus($"安全认证的错误反馈，反馈指令：{BitConverter.ToString(data[i].Data)}");
                    }
                }
            }
        }

        private async void ProcessMese8(List<CANBasic.VCI_CAN_OBJ> data)
        {
            for (int i = 0; i < data.Count; i++)
            {
                if (data[i].Data[1] == 0x50)//扩展会话模式的回复 50 03 00 32 01 F4
                {
                    if (data[i].Data[2] == 0x03)
                    {
                        //进入10 02模式
                        //SendMessage(new byte[] { 0x02, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);

                        //请求种子，发送27 01
                        SendMessage(new byte[] { 0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    }
                    //else if (data[i].Data[2] == 0x02)
                    //{
                    //    //请求种子，发送27 01
                    //    SendMessage(new byte[] { 0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    //}
                }
                else if (data[i].Data[1] == 0x67)
                {
                    if (data[i].Data[2] == 0x01)//请求种子27的回复
                    {
                        //计算密钥
                        var keys = Encipher(2, new byte[] { data[i].Data[3], data[i].Data[4], data[i].Data[5], data[i].Data[6] });

                        //发送密钥进行验证
                        SendMessage(new byte[] { 0x06, 0x67, 0x02, keys[0], keys[1], keys[2], keys[3] }, 0, 8);
                    }
                    else if (data[i].Data[2] == 0x02)//发送密钥的回复
                    {
                        //开始发送VIN码
                        byte[] vins;
                        GetVinMessage(out vins);
                        if (vins.Length > 5)//发送多帧，默认数据长度为多帧
                        {
                            SendMessage(new byte[] { 0x10, 0x14, 0x2e, 0xf1, 0x90, vins[0], vins[1], vins[2] }, 0, 8);
                        }
                    }
                }
                else if (data[i].Data[0] == 0x30)
                {
                    if (data[i].Data[1] == 0x00 && data[i].Data[2] == 0x02)
                    {
                        byte[] vins;
                        GetVinMessage(out vins);
                        for (int f = 3; f < vins.Length; f = f + 8)
                        {
                            SendMessage(vins, f, 8);
                            await Task.Delay(10);
                        }
                    }
                }
                else if (data[i].Data[1] == 0x6e)
                {
                    if (data[i].Data[2] == 0xf1 && data[i].Data[3] == 0x90)
                    {
                        //写入VIN成功
                    }
                }
                else if (data[i].Data[1] == 0x7f)//错误反馈
                {
                    if (data[i].Data[2] == 0x10)//进入10 02模式的错误反馈 0x03 0x7f 0x10 0x7e 0xaa 0xaa 0xaa 0xaa
                    {
                    }
                    else if (data[i].Data[2] == 0x27)//请求种子的错误反馈 0x03 0x7f 0x27 0x7f 0x0a 0x0a 0x0a, 0x0a
                    {
                    }
                }
            }
        }

        private async void ProcessMT05(List<CANBasic.VCI_CAN_OBJ> data)
        {
            for (int i = 0; i < data.Count; i++)
            {
                if (data[i].Data[1] == 0x50)//扩展会话模式的回复 50 03 00 32 01 F4
                {
                    if (data[i].Data[2] == 0x03)
                    {
                        //进入10 02模式
                        //SendMessage(new byte[] { 0x02, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);

                        //请求种子，发送27 01
                        SendMessage(new byte[] { 0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    }
                    //else if (data[i].Data[2] == 0x02)
                    //{
                    //    //请求种子，发送27 01
                    //    SendMessage(new byte[] { 0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    //}
                }
                else if (data[i].Data[1] == 0x67)
                {
                    if (data[i].Data[2] == 0x01)//请求种子27的回复
                    {
                        //计算密钥
                        var keys = Encipher(2, new byte[] { data[i].Data[3], data[i].Data[4], data[i].Data[5], data[i].Data[6] });

                        //发送密钥进行验证
                        SendMessage(new byte[] { 0x06, 0x67, 0x02, keys[0], keys[1], keys[2], keys[3] }, 0, 8);
                    }
                    else if (data[i].Data[2] == 0x02)//发送密钥的回复
                    {
                        //开始发送VIN码
                        byte[] vins;
                        GetVinMessage(out vins);
                        if (vins.Length > 5)//发送多帧，默认数据长度为多帧
                        {
                            SendMessage(new byte[] { 0x10, 0x14, 0x2e, 0xf1, 0x90, vins[0], vins[1], vins[2] }, 0, 8);
                        }
                    }
                }
                else if (data[i].Data[0] == 0x30)
                {
                    if (data[i].Data[1] == 0x00 && data[i].Data[2] == 0x02)
                    {
                        byte[] vins;
                        GetVinMessage(out vins);
                        for (int f = 3; f < vins.Length; f = f + 8)
                        {
                            SendMessage(vins, f, 8);
                            await Task.Delay(10);
                        }
                    }
                }
                else if (data[i].Data[1] == 0x6e)
                {
                    if (data[i].Data[2] == 0xf1 && data[i].Data[3] == 0x90)
                    {
                        //写入VIN成功
                    }
                }
                else if (data[i].Data[1] == 0x7f)//错误反馈
                {
                    if (data[i].Data[2] == 0x10)//进入10 02模式的错误反馈 0x03 0x7f 0x10 0x7e 0xaa 0xaa 0xaa 0xaa
                    {
                    }
                    else if (data[i].Data[2] == 0x27)//请求种子的错误反馈 0x03 0x7f 0x27 0x7f 0x0a 0x0a 0x0a, 0x0a
                    {
                    }
                }
            }
        }

        private async void ProcessUs61(List<CANBasic.VCI_CAN_OBJ> data)
        {
            for (int i = 0; i < data.Count; i++)
            {
                if (data[i].Data[1] == 0x50)//扩展会话模式的回复 50 03 00 32 01 F4
                {
                    if (data[i].Data[2] == 0x02)
                    {
                        //进入10 02模式
                        //SendMessage(new byte[] { 0x02, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);

                        //请求种子，发送27 07
                        SendMessage(new byte[] { 0x02, 0x27, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    }
                    //else if (data[i].Data[2] == 0x02)
                    //{
                    //    //请求种子，发送27 01
                    //    SendMessage(new byte[] { 0x02, 0x27, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
                    //}
                }
                else if (data[i].Data[1] == 0x67)
                {
                    if (data[i].Data[2] == 0x07)//请求种子27的回复
                    {
                        //计算密钥
                        var keys = Encipher(2, new byte[] { data[i].Data[3], data[i].Data[4], data[i].Data[5], data[i].Data[6] });

                        //发送密钥进行验证
                        SendMessage(new byte[] { 0x06, 0x67, 0x08, keys[0], keys[1], keys[2], keys[3] }, 0, 8);
                    }
                    else if (data[i].Data[2] == 0x08)//发送密钥的回复
                    {
                        //开始发送VIN码
                        byte[] vins;
                        GetVinMessage(out vins);
                        if (vins.Length > 5)//发送多帧，默认数据长度为多帧
                        {
                            SendMessage(new byte[] { 0x10, 0x14, 0x2e, 0xf1, 0x90, vins[0], vins[1], vins[2] }, 0, 8);
                        }
                    }
                }
                else if (data[i].Data[0] == 0x30)//继续发送多帧数据
                {
                    if (data[i].Data[1] == 0x00 && data[i].Data[2] == 0x02)
                    {
                        byte[] vins;
                        GetVinMessage(out vins);
                        for (int f = 3; f < vins.Length; f = f + 8)
                        {
                            SendMessage(vins, f, 8);
                            await Task.Delay(10);
                        }
                    }
                }
                else if (data[i].Data[1] == 0x6e)
                {
                    if (data[i].Data[2] == 0xf1 && data[i].Data[3] == 0x90)
                    {
                        //写入VIN成功
                    }
                }
                else if (data[i].Data[1] == 0x7f)//错误反馈
                {
                    if (data[i].Data[2] == 0x10)//进入10 02模式的错误反馈 0x03 0x7f 0x10 0x7e 0xaa 0xaa 0xaa 0xaa
                    {
                        LogHelper.Log.Info($"会话控制服务请求否定应答 {BitConverter.ToString(data[i].Data)}");
                    }
                    else if (data[i].Data[2] == 0x27)//请求种子的错误反馈 0x03 0x7f 0x27 0x7f 0x0a 0x0a 0x0a, 0x0a
                    {
                        LogHelper.Log.Info($"安全访问认证的种子请求否定应答 {BitConverter.ToString(data[i].Data)}");
                    }
                }
            }
        }

        private bool SendMessage(byte[] data, int startIndex, int dataLen)
        {
            if (!this.device.CANConnectStatus)
                return false;
            byte[] buffer = new byte[8];
            Array.Copy(data, startIndex, buffer, 0, dataLen);
            this.device.EtasDevice.FrameID = 0x7e0;
            this.device.EtasDevice.Data = buffer;
            this.device.EtasDevice.EsNumberOfBytes = buffer.Length;
            return this.es581.EsSendMessage(this.device);
        }

        private bool ReadDID(string didStr)
        {
            if(!this.device.CANConnectStatus)
                return false;
            didStr = didStr.ToLower().Replace("0x", "").Replace(" ", "").PadLeft(4, '0');
            byte[] data = new byte[] { 0x03, 0x22, Convert.ToByte(didStr.Substring(0, 2), 16), Convert.ToByte(didStr.Substring(2, 2), 16), 0x0, 0x0, 0x0, 0x0 };

            this.device.ModeType = DiagBasic.ModelSID.UDS_DID_Read;
            return SendMessage(data, 0, 8);
        }

        private bool GetVinMessage(out byte[] vinData)
        {
            var vinAscii = this.tb_barCode_Write.Text.Replace(" ", "").Trim();
            var vinArray = Encoding.ASCII.GetBytes(vinAscii);
            if (vinArray.Length < 17)
            {
                vinData = new byte[] { };
                return false;
            }
            vinData = vinArray;
            return true;
        }

        private byte[] Encipher(UInt32 num_rounds, byte[] send)
        {
            UInt32 v0 = BitConverter.ToUInt32(send.Reverse().ToArray(), 0);
            UInt32 v1 = BitConverter.ToUInt32(new byte[] { (byte)~send[3], (byte)~send[2], (byte)~send[1], (byte)~send[0]}, 0);
            UInt32[] k = new UInt32[] { 0x4C495551, 0x49534545, 0x444B4559, 0x414C474F };
            UInt32 sum = 0, delta = 0x9E3779B9;
            for (int i = 0; i < num_rounds; i++)
            {
                v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
                sum += delta;
                v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
            }
            var u0 = v0; 
            var u1 = v1;
            var u0Hex = Convert.ToString(v0, 16).PadLeft(8, '0');
            byte[] data = new byte[4];
            data[0] = Convert.ToByte(u0Hex.Substring(0, 2), 16);
            data[1] = Convert.ToByte(u0Hex.Substring(2, 2), 16);
            data[2] = Convert.ToByte(u0Hex.Substring(4, 2), 16);
            data[3] = Convert.ToByte(u0Hex.Substring(6, 2), 16);
            return data;
        }

        private void AnalysisUdsDid(List<CANBasic.VCI_CAN_OBJ> data, byte rPid)
        {
            var dataResult = AnalysisPidData(data, rPid, 1, true, ref this.device);
            if (!dataResult.AnalysisCompleted)
                return;
            int startIndex = 1;//did起始索引

            DidResultEntity didEntity = new DidResultEntity();
            didEntity.DidResults = ConvertMulType.ConvertStr2Byte(dataResult.CodesResult);
            didEntity.UsedDId = Convert.ToUInt16(dataResult.CodesResult[startIndex] + dataResult.CodesResult[startIndex + 1], 16);
            LogHelper.Log.Info("DID解析已完成 DID:" + didEntity.UsedDId.ToString("X4"));

            this.device.DIDAnalysisCompleted = true;

            var file = GetMessageAbsFile();
            this.es581.SaveMessageData(file);
            this.es581.SaveTextData(file, $"已读取到VIN码：{Encoding.ASCII.GetString(didEntity.DidResults.ToArray(), 3, didEntity.DidResults.Count - 3)}");

            UpdateDIDUI(didEntity);
        }

        private string GetMessageAbsFile()
        {
            var platform = "TestPlatform";
            if (this.rbtn_mese6.Checked)
                platform = this.rbtn_mese6.Text;
            else if (this.rbtn_mese8.Checked)
                platform = this.rbtn_mese8.Text;
            else if (this.rbtn_mt053.Checked)
                platform = this.rbtn_mt053.Text;
            else if (this.rbtn_us61.Checked)
                platform = this.rbtn_us61.Text;
            return this.messageFile + platform + "_" + System.DateTime.Now.ToString("yyyyMMdd");
        }

        /// <summary>
        /// 解析所有MODE服务PID
        /// </summary>
        /// <param name="dataList"></param>
        /// <param name="dstByte"></param>
        /// <param name="startIndex">sid=1/2/6/9,index=3/4, sid=3/7/a,index=2/3</param>
        /// <param name="includedFirst">是否包含第一位</param>
        /// <returns></returns>
        public DiagData AnalysisPidData(List<CANBasic.VCI_CAN_OBJ> dataList, byte dstByte, int startIndex, bool includedFirst, ref DiagData _OBDData)
        {
            //int dataLen = this._OBDData.DataCodeNumber;//单/多帧数据长度
            if (_OBDData.CodesResult.Count() > 0)
            {
                // dataLen = Convert.ToInt32(this._OBDData.CodesResult[0], 16);
            }
            foreach (var data in dataList)
            {
                var data1 = data.Data[0].ToString().PadLeft(2, '0');
                if (data1.Substring(0, 1) == "0")//单帧,直接解析数据  06 41 01 00 07 e5 e5 00
                {
                    if (data.Data[1] == dstByte)
                    {
                        _OBDData.CodesResult.Clear();
                        if (includedFirst)
                        {
                            _OBDData.DataCodeNumber = data.Data[0] - 1;
                        }
                        else
                        {
                            _OBDData.DataCodeNumber = data.Data[0] - 2;//sid=7不包含第一位（为故障码数量）
                        }
                        //this._OBDData.CodesResult.Add(dataLen.ToString("X2"));//添加数据长度
                        for (int i = startIndex; i < data.DataLen; i++)
                        {
                            if (_OBDData.CodesResult.Count < _OBDData.DataCodeNumber)
                            {
                                _OBDData.CodesResult.Add(data.Data[i].ToString("X2"));
                            }
                        }
                    }
                }
                else if (data1.Substring(0, 1) == "1")//多帧，需要发送30帧 10 09 41 7a 06 00 00 10 
                {
                    if (data.Data[2] == dstByte)//开始解析目标数据
                    {
                        _OBDData.CodesResult.Clear();
                        if (includedFirst)
                        {
                            _OBDData.DataCodeNumber = data.Data[1];
                        }
                        else
                        {
                            _OBDData.DataCodeNumber = data.Data[1] - 2;
                        }
                        //this._OBDData.CodesResult.Add(dataLen.ToString("X2"));
                        for (int i = startIndex + 1; i < data.DataLen; i++)
                        {
                            if (_OBDData.CodesResult.Count < _OBDData.DataCodeNumber)
                            {
                                _OBDData.CodesResult.Add(data.Data[i].ToString("X2"));
                            }
                        }
                        _OBDData.EtasDevice.FrameID = 0x7e0;
                        _OBDData.EtasDevice.Data = new byte[] { 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

                       this.es581.EsSendMessage(_OBDData);
                    }
                }
                else//解析多帧数据
                {
                    for (int i = 1; i < data.DataLen; i++)
                    {
                        if (_OBDData.CodesResult.Count() < _OBDData.DataCodeNumber)
                        {
                            _OBDData.CodesResult.Add(data.Data[i].ToString("X2"));
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            if (_OBDData.CodesResult.Count == _OBDData.DataCodeNumber)//当前解析完成
            {
                _OBDData.AnalysisCompleted = true;
                LogHelper.Log.Info("接收单帧/多帧全部解析完成");
            }
            else
            {
                _OBDData.AnalysisCompleted = false;
            }
            return _OBDData;
        }

        public void UpdateDIDUI(DidResultEntity didData)
        {
            this.Invoke(new Action(()=>
            {
                this.tb_barCode_Read.Text = Encoding.ASCII.GetString(didData.DidResults.ToArray(), 3, didData.DidResults.Count - 3);
            }));
        }

        private void UpdateLbxStatus(string result)
        {
            this.Invoke(new Action(()=>
            {
                this.tb_status.Text += System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + result;
                this.tb_status.SelectionStart = this.tb_status.Text.Length;
                this.tb_status.ScrollToCaret();
            }));
        }
    }
}
